//
//  ZYCAddPhotoView.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/27.
//

#import "ZYCAddPhotoView.h"
#import "ZYCAddPhotoPlaceHolderCell.h"
#import "ZYCPhotoCollectionCell.h"
#import <TZImagePickerController.h>

#define BTImageTotalNumber 9

@interface ZYCAddPhotoView ()<UICollectionViewDataSource,UICollectionViewDelegate,ZYCPhotoCollectionCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, assign) NSInteger maxImages;
@property (nonatomic, assign) NSInteger imagesCountPerRow;



@end
@implementation ZYCAddPhotoView

- (void)setDataArray:(NSMutableArray *)dataArray{
    _dataArray = dataArray;
    [self.collectionView reloadData];
}


- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.collectionHeight = 98.0f;
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];

        
    }
    return self;
}

#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.dataArray.count == BTImageTotalNumber) {
        return self.dataArray.count;
    }else{
        return self.dataArray.count + 1;
    }

}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == self.dataArray.count) {
        ZYCAddPhotoPlaceHolderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ZYCAddPhotoPlaceHolderCell class]) forIndexPath:indexPath];
        return cell;
    }else{
        ZYCPhotoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ZYCPhotoCollectionCell class]) forIndexPath:indexPath];
        cell.delegate = self;
        cell.object = self.dataArray[indexPath.item];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == self.dataArray.count) {
        [self presentFliter];
    }

}


- (void)presentFliter{
    ZYCWeakSelf
    UIAlertController *alert = [[UIAlertController alloc] init];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //判断权限
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
            [alertC addAction:action1];
            [alertC addAction:action2];
            [self.viewController presentViewController:alertC animated:YES completion:nil];
        }else {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self.viewController presentViewController:picker animated:YES completion:nil];
        }
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf pushTZImagePickerViewController];

    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.viewController dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:photoAction];
    [alert addAction:albumAction];
    [alert addAction:cancelAction];
    [self.viewController presentViewController:alert animated:YES completion:nil];
}

- (void)pushTZImagePickerViewController{
    ZYCWeakSelf
//    [weakSelf.dataArray removeAllObjects];
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 - self.dataArray.count columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    
//    if (self.selectedAssets.count > 0) {
//        imagePickerVc.selectedAssets = self.selectedAssets;
//    }
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    [imagePickerVc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    imagePickerVc.navigationBar.tintColor = [UIColor blackColor];
    imagePickerVc.naviBgColor = [UIColor whiteColor];
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.selectedAssets = [NSMutableArray arrayWithArray:assets];
        weakSelf.selectedPhotos = [NSMutableArray arrayWithArray:photos];
        [weakSelf.dataArray addObjectsFromArray:photos];
        [weakSelf.collectionView reloadData];
        if ([weakSelf.delegate respondsToSelector:@selector(addPhotosViewUpdateSaveStatus)]) {
            [weakSelf.delegate addPhotosViewUpdateSaveStatus];
        }
    }];
    [self.viewController presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    ZYCWeakSelf
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
            [weakSelf.selectedAssets addObject:asset];
            [weakSelf.selectedPhotos addObject:image];
            [weakSelf.dataArray addObject:image];
            [weakSelf.collectionView reloadData];
            if ([weakSelf.delegate respondsToSelector:@selector(addPhotosViewUpdateSaveStatus)]) {
                [weakSelf.delegate addPhotosViewUpdateSaveStatus];
            }
        }];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - ZYCPhotoCollectionCellDelegate

- (void)photoCollectionCellDidClickDelete:(ZYCPhotoCollectionCell *)cell{
    NSObject *object = cell.object;
    if ([self.delegate respondsToSelector:@selector(addPhotosViewDidClickDelete:)]) {
        [self.delegate addPhotosViewDidClickDelete:cell.object];
    }
    if ([cell.object isKindOfClass:[ZYCBusFileListModel class]]) {
        ZYCBusFileListModel * model = (ZYCBusFileListModel *)object;
        [self.dataArray removeObject:model];
    }else{
        UIImage * image = (UIImage *)object;
        [self.selectedPhotos removeObject:image];
        [self.selectedAssets removeObject:image];
    }
//    [self.dataArray removeObject:cell.object];
    [self.collectionView reloadData];
}

#pragma mark - private method
- (void)layoutNewFrame{
    // 如果参数是小数  则求最小的整数但不小于本身.
    NSInteger lineCount = ceil(self.dataArray.count / 3) + 1;
    CGFloat imgItemWidth = 98.0f;
    self.collectionHeight = lineCount *(10 + imgItemWidth);
//    [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
//
//        self.collectionHeight = lineCount *(10 + imgItemWidth);
//    }];
    
//    self.collectionView.frame = CGRectMake(0, 0, self.frame.size.width, lineCount *(10 + imgItemWidth));
//    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.collectionView.frame.size.height);
}

#pragma mark - getters
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerClass:[ZYCAddPhotoPlaceHolderCell class] forCellWithReuseIdentifier:NSStringFromClass([ZYCAddPhotoPlaceHolderCell class])];
        [_collectionView registerClass:[ZYCPhotoCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([ZYCPhotoCollectionCell class])];
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.itemSize = CGSizeMake(98.0, 98.0f);
        _layout.minimumLineSpacing = 0;//行间距
        _layout.minimumInteritemSpacing = 0;//列间距
        _layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return _layout;
}

- (NSMutableArray *)selectedPhotos {
    if (!_selectedPhotos) {
        _selectedPhotos = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectedPhotos;
}


- (NSMutableArray *)selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectedAssets;
}

@end


//实现获取视图所在控制器的扩展
@implementation UIView (Extend)
- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

@end
